package com.business.dashboard.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.business.dashboard.entity.BusinessPlan;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * 商业计划书数据访问层
 * 
 * @author Claude
 * @since 2025-07-06
 */
@Mapper
public interface BusinessPlanDao extends BaseMapper<BusinessPlan> {

    /**
     * 查询商业计划书列表（分页）
     */
    @Select("<script>" +
            "SELECT * FROM business_plans WHERE deleted = 0 " +
            "<if test='keyword != null and keyword != \"\"'>" +
            "AND (title LIKE CONCAT('%', #{keyword}, '%') OR company_name LIKE CONCAT('%', #{keyword}, '%')) " +
            "</if>" +
            "<if test='status != null and status != \"\"'>" +
            "AND status = #{status} " +
            "</if>" +
            "<if test='industry != null and industry != \"\"'>" +
            "AND industry = #{industry} " +
            "</if>" +
            "<if test='userId != null'>" +
            "AND user_id = #{userId} " +
            "</if>" +
            "ORDER BY created_at DESC LIMIT #{offset}, #{size}" +
            "</script>")
    List<BusinessPlan> selectPlanList(@Param("offset") int offset,
                                     @Param("size") int size,
                                     @Param("keyword") String keyword,
                                     @Param("status") String status,
                                     @Param("industry") String industry,
                                     @Param("userId") Long userId);

    /**
     * 根据状态统计商业计划书数量
     */
    @Select("SELECT COUNT(*) FROM business_plans WHERE status = #{status} AND deleted = 0")
    int countByStatus(@Param("status") String status);

    /**
     * 根据用户ID统计商业计划书数量
     */
    @Select("SELECT COUNT(*) FROM business_plans WHERE user_id = #{userId} AND deleted = 0")
    int countByUserId(@Param("userId") Long userId);

    /**
     * 更新查看次数
     */
    @Update("UPDATE business_plans SET view_count = view_count + 1 WHERE id = #{id}")
    int updateViewCount(@Param("id") Long id);

    /**
     * 更新下载次数
     */
    @Update("UPDATE business_plans SET download_count = download_count + 1 WHERE id = #{id}")
    int updateDownloadCount(@Param("id") Long id);

    /**
     * 根据分享码查询商业计划书
     */
    @Select("SELECT * FROM business_plans WHERE share_code = #{shareCode} AND deleted = 0")
    BusinessPlan selectByShareCode(@Param("shareCode") String shareCode);

    /**
     * 获取热门商业计划书列表
     */
    @Select("SELECT * FROM business_plans WHERE deleted = 0 ORDER BY view_count DESC, download_count DESC LIMIT #{limit}")
    List<BusinessPlan> selectPopularPlans(@Param("limit") int limit);
}